﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MvcEx.Partials
{
    public static class PartialActionHelper
    {
        /// <summary>
        /// Renders a partial view, but gets the model for the view from a method on the current controller
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="name"></param>
        public static void RenderDynamicPartial(this HtmlHelper helper, String name)
        {
            // Find the relevant method on the relevant controller
            var method = helper.ViewContext.Controller.GetType().GetMethod(name);

            // It's not mandatory that we get a method
            if (method == null)
            {
                helper.RenderPartial(name);
            }
            else
            {
                // Get the model from the method exposed
                Object model = method.Invoke(helper.ViewContext.Controller, null);

                // Proxy the call across to RenderPartial
                helper.RenderPartial(name, model);
            }
        }
    }
}
